'use strict';
const db = uniCloud.database();
const $ = db.command;

exports.main = async (event, context) => {
	// 控制台日志输出
	console.log('event : ', event);
	try {
		let userInfo = {};
		if (event.userId) {
			const getUserInfo = await db.collection('userList')
				.where({ _id: event.userId })
				.field({ roleId: 1 }) // 只查询roleId字段
				.get();
			userInfo = getUserInfo.data[0] || {};
		}
		
		const allRolesRes = await db.collection('role')
			.field({ menus: 1, _id: 1 }) // 只获取需要的字段
			.get();
		const allRoles = allRolesRes.data || [];
		
		let roleInfo = {};
		const targetRoleId = userInfo.roleId || '68dd3ecb8a5c78a4a92766c2'; // 游客角色ID
		roleInfo = allRoles.find(role => role._id === targetRoleId) || {};
		
		const parentIds = [];
		const childIds = [];
		
		if (roleInfo._id && Array.isArray(roleInfo.menus)) {
			roleInfo.menus.forEach(menuPermission => {
				if (menuPermission.parentId && !parentIds.includes(menuPermission.parentId)) {
					parentIds.push(menuPermission.parentId);
				}
				if (Array.isArray(menuPermission.children)) {
					menuPermission.children.forEach(childId => {
						if (!childIds.includes(childId)) {
							childIds.push(childId);
						}
					});
				}
			});
		}
		
		let parentMenusMap = {};
		if (parentIds.length > 0) {
			const parentMenuRes = await db.collection('menu')
				.where({ _id: $.in(parentIds) , location: event.location })
				.orderBy('createTime', 'desc')
				.get();
			
			parentMenuRes.data.forEach(menu => {
				parentMenusMap[menu._id] = menu;
			});
		}
		
		let childMenusMap = {};
		if (childIds.length > 0) {
			const childMenuRes = await db.collection('menuDetail')
				.where({ _id: $.in(childIds) })
				.orderBy('createTime', 'desc')
				.get();
			
			childMenuRes.data.forEach(menu => {
				childMenusMap[menu._id] = menu;
			});
		}
		
		const dataList = [];
		if (roleInfo._id && Array.isArray(roleInfo.menus)) {
			roleInfo.menus.forEach(menuPermission => {
				const parentMenu = parentMenusMap[menuPermission.parentId];
				if (!parentMenu?._id) return; // 跳过不存在的父菜单
				
				const menuItem = {
					_id: parentMenu._id,
					className: parentMenu.className,
					createTime: parentMenu.createTime || new Date().toISOString().split('T')[0],
					children: []
				};
				
				if (Array.isArray(menuPermission.children) && menuPermission.children.length > 0) {
					menuPermission.children.forEach(childId => {
						const childMenu = childMenusMap[childId];
						if (childMenu?._id) {
							menuItem.children.push({
								_id: childMenu._id,
								className: parentMenu.className,
								classId: parentMenu._id,
								iconUrl: childMenu.iconUrl || '',
								menuName: childMenu.menuName || '',
								createTime: childMenu.createTime || new Date().toISOString().split('T')[0],
								pathUrl: childMenu.pathUrl || ''
							});
						}
					});
				}
				
				dataList.push(menuItem);
			});
		}
		
		return {
			code: 200,
			message: "操作成功",
			data: dataList
		};
	} catch (error) {
		console.error('权限查询错误:', error);
		return {
			code: 500,
			message: "查询失败",
			data: []
		};
	}
};
    